/**
 * LibraryManager.java
 * -- Short Description Here --
 *
 * @author:  John Thomason
 *  Course:  CS223
 *  Assign:
 * Seminar:
 *    Date:  Feb 16, 2009
 */

// Assigned Package
package libman;

// Package Imports
import libman.db.*;
import java.util.*;

/**
 * LibraryManager Class
 */
public class LibraryManager
implements LibManModel
{
    //Instance Variables
    LibManDAO dao;
    ArrayList<LibManView> views = new ArrayList<LibManView>();
    
    //Constructors
    public LibraryManager(){
        try {
            dao = new LibManDAOImpl();
        }
        catch (Exception e){
            System.err.println(e.getMessage());
        }
    }//LibraryManager Constructor

    public void addChangeListener(LibManView lmv) throws LibManException {
        views.add(lmv);
    }//addChangeListener

    public void addBook(Book book) throws LibManException {
        try {
            dao.create(book);
            fireModelChangeEvent(book);
        }//try
        catch (Exception e) {
            throw new LibManException("LibManModelImpl.addBook::" +
                    e.getMessage());
        }//catch
    }//addBook()

    public void deleteBook(Book book) throws LibManException {
        try {
            dao.delete(book);
            fireModelChangeEvent(book);
        }//try
        catch (Exception e) {
            throw new LibManException("LibManModelImpl.addBook::" +
                    e.getMessage());
        }//catch
    }//deleteBook()

    public Book findBook(String needle) throws LibManException {
        Book book = null;
        try {
            book = dao.read(needle);
        }//try
        catch (Exception e){
            throw new LibManException("LibManModelImpl.findBook::" +
                    e.getMessage());
        }//catch
        return book;
    }//findBook()

    public Book[] listBooks() throws LibManException {
        Book[] books = null;
        try {
            books = dao.readAll();
        }//try
        catch (Exception e){
            throw new LibManException("LibManModelImpl.findBook::" +
                    e.getMessage());
        }//catch
        return books;
    }//listBooks()

// Private Support Methods ****************************************************

    private void fireModelChangeEvent(Book book) {
        //foreach view...
        for (LibManView v: views) {
            try {
                v.handleBookChange(book);
            }//try
            catch(Exception e) {
                e.printStackTrace();
            }//catch
        }//foreach

    }//fireModelChangeEvent()

}//LibraryManager Class
